<?php defined('BASEPATH') or exit('No direct script access allowed');

class Upload extends FrontendController 
{
	public function ckeditor()
	{
		// Debug
		$this->output->enable_profiler(false);
		$this->load->library('upload');
		$CKEcallback = $this->input->get('CKEditorFuncNum');
		$files = $_FILES;
		$url = '';
		$msg = '';
		$field = '';
		foreach($files as $key=>$val)
		{
			$field = $key;
			$img = $val;
			break;
		}
		if(isset($img) && $img['error'] == 0)
		{
			$date_path = date('Y'). '/' .date('m');
			$upload_path = FCPATH. DIRECTORY_SEPARATOR .trim($this->config->item('folder_image'), '/');
			$upload_path .= DIRECTORY_SEPARATOR .$date_path;
			$upload_path = path_clean($upload_path);
			folder_create($upload_path);

			$ext = '.'.file_getExt($img['name']);
			$fname = basename($img['name'], $ext);
			$fname = time().'_'.urlTitle($fname).$ext;
			$config = array(
				'upload_path' => $upload_path,
				'file_name' => $fname,
				'allowed_types' => $this->config->item('allowed_types'),
				'max_size' => $this->config->item('max_filesize'),
				'max_width' => $this->config->item('max_image_width'),
				'max_height' => $this->config->item('max_image_height')
			);
			$this->upload->initialize($config);
			if($this->upload->do_upload($field))
			{
				$img = $this->upload->data();
				$url = base_url().trim($this->config->item('folder_image'), '/').'/'.$date_path. '/'. $img['file_name'];
				$msg = lang('upload_successful');
			}
			else
			{
				$msg = $this->upload->display_errors();
			}
		}

		$data = array(
			'ckecallback' => $CKEcallback,
			'url' => $url,
			'msg' => strip_tags($msg),
		);
		$this->load->view('upload/ckeditor', $data);
	}
}

